/*
* Copyright (c) 2007 by Kirill Kolodyazhniy.
* See the file "license.terms" for information on usage and redistribution.
*/

#include "archivemanager.h"
#include "log.h"
#include "archive.h"

namespace Engine
{
	using namespace std;
	/**********************************************************************************************************/
	template<> ArchiveManager* Singleton<ArchiveManager>::m_singleton = 0;
	/***************************************************************************************************************/
	void ArchiveManager::AddPath( const std::string& filename, const std::string& archiveType)
	{
		Lock lock;
		ArchivesMap::iterator arch = m_loadedArchives.find(filename);
		if(arch == m_loadedArchives.end())
		{
			FactoriesMap::iterator fact = m_factories.find(archiveType);
			if(fact != m_factories.end())
			{
				RefPtr<Archive> pArch(fact->second->CreateInstance(filename));
				m_loadedArchives.insert(ArchivesMap::value_type(filename,pArch));				
				return;
			}
		}		
		Log::GetSingleton() << "Can't find decoder for archive \"" << filename << "\" with type \"" << archiveType << "\"" << endl;		
	}
	/***************************************************************************************************************/
	void ArchiveManager::AddArchiveFactory(ArchiveFactoryPtr factory)
	{
		Lock lock;
		m_factories.insert(FactoriesMap::value_type(factory->GetType(),factory));
	}
	/**********************************************************************************************************/
	RefPtr<DataStream> ArchiveManager::ReadFile(const std::string& name) const
	{
		Lock lock;
		ArchivesMap::const_iterator i = m_loadedArchives.begin(), e = m_loadedArchives.end();
		for(;i != e; ++i)
		{
			Archive::VectorStringPtr files = i->second->Find(name);
			if(!files.IsNull() && !files->empty())			
				return RefPtr<DataStream>(i->second->ReadFile(files->at(0)));
		}
		return RefPtr<DataStream>();
	}
	/***************************************************************************************************************/
}

